import React, { useState } from 'react';
import { connect, Dispatch } from 'umi';

import { Empty, Tabs, Dropdown, Menu, Modal, message } from 'antd';
const { TabPane } = Tabs;
const { confirm } = Modal;

import { MenuUnfoldOutlined, ExclamationCircleOutlined } from '@ant-design/icons';

import styles from './style.less';

import WidgetBoardList from '@/components/WidgetBoardList';
const RenameModel = React.lazy(() => import('./RenameModel'));
const AddModel = React.lazy(() => import('./AddModel'));

import {
  dashboardGroupsItem,
  PanelsItem,
  dashboardWidgetsItem,
  IDashboardItem,
} from '@/pages/SelfQuery/type';
import { ConnectState, IResponse } from '@/models/connect';

interface WidgetGroupProps {
  groups: Array<dashboardGroupsItem>;
  dispatch: Dispatch;
  panelsItem: PanelsItem | any;
  dashboard: IDashboardItem;
  removeWidgets?: (id: number) => void;
}

const WidgetGroup: React.FC<WidgetGroupProps> = (props) => {
  const { groups, dispatch, panelsItem, removeWidgets, dashboard } = props;
  const [renameModalVisible, SetRenameModalVisible] = useState<boolean>(false); // 重命名弹框
  const [indexModalVisible, SetIndexModalVisible] = useState<boolean>(false); // 添加指标弹框
  const [operationGroup, SetOperationGroup] = useState<dashboardGroupsItem | any>(groups[0]); // 操作的组 默认第一个
  const [activeKey, setActiveKey] = useState<string>(String(groups[0].id)); // 激活的面板

  // 更改显示面板
  const onChange = (key: string) => {
    setActiveKey(key);
    groups.map((item: dashboardGroupsItem) => {
      if (item.id === Number(key)) {
        SetOperationGroup(item);
      }
    });
  };

  // 重命名
  const rename = (id: number) => {
    SetRenameModalVisible(true);
  };

  // 添加指标
  const add = (id: number) => {
    groups.forEach((item: dashboardGroupsItem) => {
      if (item.id === id) {
        SetOperationGroup(item);
      }
    });
    SetIndexModalVisible(true);
  };

  // 删除分组
  const remove = (id: number) => {
    confirm({
      title: '确认要删除分组吗?',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'board/deletGroup',
          payload: {
            id,
          },
          callback: (res: IResponse) => {
            const { header } = res;
            if (header.code === 200) {
              message.success('删除成功');
              // 重新赋值看板详情数据
              const newDashboard: IDashboardItem = JSON.parse(JSON.stringify(dashboard));
              newDashboard.groups = newDashboard.groups.filter(v => v.id !== id)

              if(newDashboard.groups.length) {
                setActiveKey(String(newDashboard.groups[0].id))

              }
              dispatch({
                type: 'panel/sevaDashboard',
                payload: newDashboard,
              });

            } else {
              message.warning('删除失败');
            }
          },
        });
      },
    });
  };

  // 分组删除指标
  const groupRemoveWidget = (id: number) => {
    confirm({
      title: '确认要移除指标吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        let operationGroupNew = {...operationGroup}
        let widgets: Array<dashboardWidgetsItem> = operationGroupNew.WidgetsArr.filter(
          (item: dashboardWidgetsItem) => item.id !== id,
        );
        operationGroupNew.WidgetsArr = widgets
        const widgetsID: Array<number> = [];
        widgets.map((v: dashboardWidgetsItem) => {
          widgetsID.push(v.widgetId);
        });

        dispatch({
          type: 'board/updateGroup',
          payload: { id: operationGroup.id, widgets: widgetsID },
          callback: (res: IResponse) => {
            const { header } = res;
            if (header.code === 200) {
              SetOperationGroup(operationGroupNew)
              message.success('移除指标成功');
              // 重新赋值看板详情数据
              const newDashboard: IDashboardItem = JSON.parse(JSON.stringify(dashboard));
              newDashboard.groups.map((v) => {
                if (v.id === operationGroup.id) {
                  v.widgets = widgetsID.toString();
                }
                return v;
              });

              dispatch({
                type: 'panel/sevaDashboard',
                payload: newDashboard,
              });
            } else {
              message.warning('移除指标失败');
            }
          },
        });
      },
    });
  };

  // 自定义头部
  const renderTabBar = (props: any, DefaultTabBar: any) => {
    return (
      <DefaultTabBar {...props}>
        {(node: any) => {
          {
            /* 操作对象为空时，不展示操作 */
          }
          if (panelsItem) {
            return (
              <div
                className={node.props.children !== '未分组' ? styles.tabBar : styles.tabline}
                key={node.key}
              >
                {node}
                {node.props.children !== '未分组' && (
                  <p className={styles.menu}>
                    <Dropdown
                      placement="bottomRight"
                      overlay={
                        <Menu>
                          <Menu.Item
                            onClick={() => {
                              add(Number(node.key));
                            }}
                          >
                            添加指标
                          </Menu.Item>
                          <Menu.Item
                            onClick={() => {
                              rename(Number(node.key));
                            }}
                          >
                            重命名
                          </Menu.Item>
                          <Menu.Item
                            onClick={() => {
                              remove(Number(node.key));
                            }}
                          >
                            删除分组
                          </Menu.Item>
                        </Menu>
                      }
                    >
                      <MenuUnfoldOutlined />
                    </Dropdown>
                  </p>
                )}
              </div>
            );
          }
          return node;
        }}
      </DefaultTabBar>
    );
  };

  return (
    <div className={styles.widgetGroup}>
      <Tabs type="card" onChange={onChange} activeKey={activeKey} renderTabBar={renderTabBar}>
        {groups.map((item: dashboardGroupsItem) => (
          <TabPane tab={item.groupName} key={String(item.id)}>
            {item.WidgetsArr.length ? (
              <WidgetBoardList
                widgets={item.WidgetsArr}
                manage={panelsItem ? true : false}
                removeWidgets={item.groupName === '未分组' ? removeWidgets : groupRemoveWidget}
              />
            ) : (
              <Empty description="该分组暂无指标" style={{marginTop: '50px'}}/>
            )}
          </TabPane>
        ))}
      </Tabs>

      {/* 重命名弹框 */}
      {renameModalVisible && operationGroup && (
        <React.Suspense fallback={null}>
          <RenameModel
            visible={renameModalVisible}
            onCancel={() => SetRenameModalVisible(false)}
            operationGroup={operationGroup}
            panelsItem={panelsItem}
          />
        </React.Suspense>
      )}

      {/* 添加指标弹框 */}
      {indexModalVisible && operationGroup && (
        <React.Suspense fallback={null}>
          <AddModel
            visible={indexModalVisible}
            onCancel={() => SetIndexModalVisible(false)}
            groups={groups}
            operationGroup={operationGroup}
          />
        </React.Suspense>
      )}
    </div>
  );
};

export default connect(({ panel }: ConnectState) => ({
  dashboard: panel.dashboard,
}))(WidgetGroup);
